/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Yongke
 */
@WebServlet(name="ChatProcessing", urlPatterns={"/ChatProcessing"})
public class ChatProcessing extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            HttpSession session = request.getSession();
            //
            String userlogin = session.getAttribute("username").toString();
            String content = request.getParameter("chatcontent");
            if (content.charAt(0) == '/')
            {
                String[] CP = content.split(" ");
                if (CP[0].equals("/create"))
                {
                    Connection conn = null;
                    Statement stmt = null;
                    ResultSet rs = null;
                    try {
                        Class.forName("com.mysql.jdbc.Driver").newInstance();
                        conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/myrc?" + "user=progin&password=progin");
                        stmt = (Statement) conn.createStatement();
                        if (stmt.execute("SELECT * FROM user WHERE Username='" + session.getAttribute("username") + "'"))
                        {
                            rs = stmt.getResultSet();
                        }
                        rs.next();
                        int maxroom = rs.getInt("NumRoom");
                        if (memori.Room.getNOfRoom(session.getAttribute("username").toString()) == maxroom)
                        {
                            out.print("You've reach the maximum number of rooms allowed.");
                        }
                        else
                        {
                            if (CP.length == 3)
                            {
                                if (memori.Room.containingRoom(CP[1]))
                                {
                                    out.print("Room with the same name already exist.");
                                }
                                else
                                {
                                    
                                    memori.Room.AddRoom(new Room(CP[1], session.getAttribute("username").toString(), Integer.parseInt(CP[2])));
                                    out.print("Room has been created.");
                                }
                            }
                            else if (CP.length == 2)
                            {out.print("Test2.");
                                if (memori.Room.containingRoom(CP[1]))
                                {
                                    out.print("Room with the same name already exist.");
                                }
                                else
                                {
                                    memori.Room.AddRoom(new Room(CP[1], session.getAttribute("username").toString(), Integer.parseInt(request.getParameter("currentcategory"))));
                                    out.print("Room has been created.");
                                }
                            }
                            else
                            {
                                out.print("Wrong command parameter. Type '/help' for help.");
                            }
                        }
                    }
                    catch (SQLException ex)
                    {
                        out.println("SQLException: " + ex.getMessage());
                        out.println("SQLState: " + ex.getSQLState());
                        out.println("VendorError: " + ex.getErrorCode());
                    }
                    catch (Exception ex)
                    {
                        out.println(ex.toString());
                    }
                }
                else if(CP[0].equals("/join"))
                {
					out.println("Anda join room "+CP[1]);
                //join room
                }
                else if(CP[0].equals("/chat"))
                {
					out.println("Anda chat dengan teman : "+CP[1]);
                //melakukan chat
                }
                else if (CP[0].equals("/addfriend"))
                {
                    if (CP.length == 2)
                    {
                        Connection conn = null;
                        Statement stmt = null;
                        ResultSet rs = null;
                        try
                        {
                            Class.forName("com.mysql.jdbc.Driver").newInstance();
                            conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/myrc?" + "user=progin&password=progin");
                            stmt = (Statement) conn.createStatement();
                            Statement state = null;
                            ResultSet res = null;
                            state = (Statement) conn.createStatement();
                            if (state.execute("SELECT * FROM user WHERE Username='" + CP[1] + "'"))
                            {
                                res = state.getResultSet();
                            }
                            if (res.next())
                            {
                                if (stmt.execute("SELECT * FROM friend WHERE (Username='" + session.getAttribute("username") + "'"
                                        + " AND UNFriend='" + CP[1] + "')"))
                                {
                                    rs = stmt.getResultSet();
                                }
                                if (rs.next())
                                {
                                    out.print("This user is already your friend.");
                                }
                                else
                                {
                                    if (stmt.executeUpdate("INSERT INTO friend(Username, UNFriend) VALUES ('" + session.getAttribute("username")
                                            + "','" + CP[1] + "')") == 1)
                                    {
                                        out.print("Adding friend successful.");
                                    }
                                    else
                                    {
                                        out.print("Adding friend failed.");
                                    }
                                }
                            }
                            else
                            {
                                out.print("There is no user with this username. Thanks.");
                            }
                        }
                        catch (SQLException ex)
                        {
                            out.println("SQLException: " + ex.getMessage());
                            out.println("SQLState: " + ex.getSQLState());
                            out.println("VendorError: " + ex.getErrorCode());
                        }
                        catch (Exception ex)
                        {
                            out.println(ex.toString());
                        }
                    }
                    else
                    {
                        out.print("Wrong command parameter. Type '/help' for help.");
                    }
                //add friend
                }
                else if (CP[0].equals("/exit"))
                {
					out.println("Anda telah keluar dari room yang bersangkutan!");
                //keluar
                }
                else if (CP[0].equals("/info"))
                {
                    if (CP.length == 2)
                    {
//                        if (globalvar.RL.getRoom(R, AS[1]))
//                        {
//                        //inforoom
//                        }
//                        else
//                        {
                            Connection conn = null;
                            Statement stmt = null;
                            ResultSet rs = null;
                            try
                            {
                                Class.forName("com.mysql.jdbc.Driver").newInstance();
                                conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/myrc?" + "user=progin&password=progin");
                                stmt = (Statement) conn.createStatement();
                                if (stmt.execute("SELECT * FROM user WHERE username='" + CP[1] + "'"))
                                {
                                    rs = stmt.getResultSet();
                                }
                                if (rs.next())
                                {
                                    out.println("User info:<br />");
                                    out.println("Username: " + rs.getString("Username") + "<br />");
                                    out.println("Name: " + rs.getString("Name") + "<br />");
                                    out.println("Enmail: " + rs.getString("Email") + "<br />");
                                    if (rs.getInt("role") == 1)
                                    {
                                        out.println("Role: user moderator<br />");
                                    }
                                    else
                                    {
                                        out.println("Role: user biasa<br />");
                                    }
                                }
                                else
                                {
                                    out.print("No user and room with given name");
                                }
                            }
                            catch (SQLException ex)
                            {
                                out.println("SQLException: " + ex.getMessage());
                                out.println("SQLState: " + ex.getSQLState());
                                out.println("VendorError: " + ex.getErrorCode());
                            }
                            catch (Exception ex)
                            {
                                out.println(ex.toString());
                            }
//                        }
                    }
                    else if (CP.length == 1)
                    {
////                        if //inforoom
////                        {
////                        }
////                        else
////                        {
//                            Connection conn = null;
//                            Statement stmt = null;
//                            ResultSet rs = null;
//                            try
//                            {
//                                Class.forName("com.mysql.jdbc.Driver").newInstance();
//                                conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/myrc?" + "user=progin&password=progin");
//                                stmt = (Statement) conn.createStatement();
//                                if (stmt.execute("SELECT * FROM user WHERE username='" + request.getParameter("receiver") + "'"))
//                                {
//                                    rs = stmt.getResultSet();
//                                }
//                                if (rs.next())
//                                {
//                                    out.println("User info:<br />");
//                                    out.println("Username: " + rs.getString("username") + "<br />");
//                                    out.println("Name: " + rs.getString("name") + "<br />");
//                                    if (rs.getInt("role") == 1)
//                                    {
//                                        out.println("Role: user moderator<br />");
//                                    }
//                                    else
//                                    {
//                                        out.println("Role: user biasa<br />");
//                                    }
//                                }
//                                else
//                                {
//                                    out.print("No user and room with given name");
//                                }
//                            }
//                            catch (SQLException ex)
//                            {
//                                out.println("SQLException: " + ex.getMessage());
//                                out.println("SQLState: " + ex.getSQLState());
//                                out.println("VendorError: " + ex.getErrorCode());
//                            }
//                            catch (Exception ex)
//                            {
//                                out.println(ex.toString());
//                            }
////                        }
//                    }
//                    else
//                    {
//                        out.print("Wrong command parameter. Type '/help' for help.");
//                    }                //menampilkan informasi room
                }
                }
                else if (CP[0].equals("/kick"))
                {
					out.println("Anda meng-kick"+CP[1]);
                //
                }
                else if (CP[0].equals("/ban"))
                {
					out.println("Anda melakukan ban terhadap"+CP[1]);
                //ban user
                }
                else if (CP[0].equals("/unban"))
                {
					out.println("Anda melakukan unban terhadap"+CP[1]);
                //unban
                }
                else if (CP[0].equals("/persist"))
                {
					out.println("anda persist room"+CP[1]);
                //persist
                }
                else if (CP[0].equals("/setowner"))
                {
					out.println("Anda melakukan set owner pada"+CP[1]);
                //set owner
                }
                else if (CP[0].equals("/help"))
                {
                    out.println("Available command : <br />");
                    out.println("/create <roomname>[category id] <br />");
                    out.println("/join <roomname><br />");
                    out.println("/chat <username><br />");
                    out.println("/addfriend <username><br />");
                    out.println("/exit<br />");
                    out.println("/info [roomname|username]<br />");
                    out.println("These commands are for room owner only:<br />");
                    out.println("/kick <username><br />");
                    out.println("/ban <username><br />");
                    out.println("/unban <username><br />");
                    out.println("/persist <on|off><br />");
                    out.println("/setowner <username>");
                }
                else
                {
                    out.print("Command invalid. Type '/help' for help.");
                }
            }
            else
            {
            }
        } finally {
            out.close();
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
